package my.diplom.web.controllers;

import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.validation.BindException;
import org.apache.log4j.Logger;
import my.diplom.dao.service.ApplicationService;
import my.diplom.dao.service.StatusService;
import my.diplom.dao.service.CategoryService;
import my.diplom.entity.Category;
import my.diplom.entity.Application;
import my.diplom.entity.Status;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.List;
import java.util.HashMap;
import java.beans.PropertyEditorSupport;


/**
 * Created by IntelliJ IDEA.
 * User: gb
 * Date: 29.07.2009
 * Time: 0:27:24
 * To change this template use File | Settings | File Templates.
 */
public class ApplicationController extends SimpleFormController {

     private static final Logger log = Logger.getLogger(ApplicationController.class);

    private ApplicationService applicationService;
    private StatusService statusService;
    private CategoryService categoryService;

    public ApplicationController(){
        setCommandClass(Application.class);
        setCommandName("newApplication");
        setSessionForm(false);
        setBindOnNewForm(false);

    }

    public void setApplicationService(ApplicationService applicationService) {
        this.applicationService = applicationService;
    }

    public void setStatusService(StatusService statusService) {
        this.statusService = statusService;
    }

    public void setCategoryService(CategoryService categoryService) {
        this.categoryService = categoryService;
    }

    protected Map referenceData(HttpServletRequest request) throws Exception {
        List<Category> categories = categoryService.getAll();
        HashMap<String, Object> model = new HashMap<String, Object>();
        model.put("cats", categories);
        return model;
    }

    protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o, BindException e) throws Exception {
        Application application = (Application) o;
        applicationService.create(application);
        return new ModelAndView(new RedirectView("createApplication.htm"));
    }


     protected Object formBackingObject(HttpServletRequest request) throws Exception {
        if (request.getParameter("applicationId") != null && request.getParameter("action").equals("edit")) {
            Application application = applicationService.getById(Long.parseLong(request.getParameter("applicationId")));
            return application;
        } else {
            Application application = new Application();
            return application;
        }
    }

     protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
          binder.registerCustomEditor(Status.class, "status", new PropertyEditorSupport() {

            public void setAsText(String text) {
                if (text instanceof String) {
                    if (text.equals("inactive")) {
                        Status status = statusService.getByName("inactive");
                        setValue(status);
                    } else if (text.equals("active")) {
                        Status status = statusService.getByName("active");
                        setValue(status);
                    }

                }
            }

            public String getAsText() {
                Object value = getValue();
                if (value != null) {
                    Status status = (Status) value;
                    return status.getStatusName();
                }
                return null;
            }


        });


         binder.registerCustomEditor(Category.class, "category", new PropertyEditorSupport(){
              public void setAsText(String text) {
                  if (text != null || text.trim().length()  > 0) {
                      if (text instanceof String) {
                          Category category = categoryService.getByName(text);
                          setValue(category);
                      }
                  }
              }

            public String getAsText() {
                Object value = getValue();
                if (value != null) {
                    Category category = (Category) value;
                    return category.getCategoryName();
                }
                return null;
            }

         });

     }

    @Override
    protected ModelAndView showForm(HttpServletRequest request, HttpServletResponse response, BindException errors) throws Exception {
        return super.showForm(request, response, errors); 
    }
}
